﻿using RabbitMQ.Client;
using System;
using System.Text;
using System.Threading;

namespace _1._1SimpleSend
{
    /// <summary>
    /// 消息发送端
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            //1.1.实例化连接工厂
            var factory = new ConnectionFactory()
            {
                UserName = "admin",//用户名
                Password = "admin",//密码
                HostName = "192.168.0.248" //rabbitmq ip
            };
            int msgCout = 1000;
            string msg = "发送的消息";

            //2. 建立连接
            using (var connection = factory.CreateConnection())
            {
                //3. 创建信道
                using (var channel = connection.CreateModel())
                {
                    //4. 声明一个队列(指定durable:true,告知rabbitmq对消息进行持久化)
                    channel.QueueDeclare(queue: "hello", durable: true, exclusive: false, autoDelete: false, arguments: null);
                    //将消息标记为持久性 - 将IBasicProperties.SetPersistent设置为true
                    var properties = channel.CreateBasicProperties();
                    properties.Persistent = true;

                    //4.1 使用direct exchange来发送消息
                    //申明direct类型exchange
                    channel.ExchangeDeclare(exchange: "directEC", type: "direct");
                    //绑定队列到direct类型exchange，需指定路由键routingKey
                    channel.QueueBind(queue: "hello", exchange: "directEC", routingKey: "hello");

                    Console.WriteLine("消息发送端已启动 \nRabbitMQ连接成功，正在发送消息...\n");
                    

                    //循环发送消息
                    for (int i = 0; i < msgCout; i++)
                    {
                        var message = msg + i;
                        //5. 构建byte消息数据包
                        var body = Encoding.UTF8.GetBytes(message);

                        //6. 发送数据包(指定basicProperties)
                        //6.1 直接发布到队列中
                        //channel.BasicPublish(exchange: "", routingKey: "hello", basicProperties: properties, body: body);

                        //6.2 发布到exchange，类型direct，必须指定routingKey
                        channel.BasicPublish(exchange: "directEC", routingKey: "hello", basicProperties: properties, body: body);

                        Console.WriteLine(" 发送消息: {0}", message);

                        //Thread.Sleep(500);//模拟耗时
                    }
                }
            }

            Console.WriteLine("\n发送结束\n输入 [enter] 退出程序.\n");
            //程序不结束，等待输入
            Console.ReadLine();
        }
    }
}
